<?php

namespace App\Traits;

use App\Models\FileTransaction;
use App\Models\Qiniu;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Http\FormRequest;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

trait WithFile
{
    protected $model;

    protected function upload(array $plucks = [], FormRequest $request, string $file = 'public')
    {
        foreach ($plucks as $key => $value) {
            if (!$request->hasFile($value)) {
                !is_null($request->input($value)) && $this->model->$value = $request->input($value);
                continue;
            }
            $file_f = $request->file($value);
            $path = \Storage::putFile($file . '/' . $value, $file_f);
            $config = Qiniu::where(['bucket' => $value])->first();
            $fileTransaction = $this->addFile($file_f, $path, $config);
            $this->model->$value = $fileTransaction->id;
        }
        $this->model->author_id = \Auth::user()->id;
        $this->model->save();
        return $this->model;
    }

    protected function setModel(Model $model)
    {
        $this->model = $model;
        return $this;
    }

    protected function addFile($file, $path, $config = null)
    {
        $fileTransaction = new FileTransaction();
        $fileTransaction->author_id = \Auth::user()->id;
        $fileTransaction->config_id = !empty($config) ? $config->id : null;
        $fileTransaction->name = $file->getClientOriginalName();
        $fileTransaction->path = \Storage::url($path);
        $fileTransaction->file_path = $path;
        $fileTransaction->size = $file->getSize();
        $fileTransaction->mime_type = $file->getMimeType();
        $fileTransaction->is_upload = false;
        $fileTransaction->status = true;
        $fileTransaction->save();
        return $fileTransaction;
    }
}